package de.herzog.bbp.view.javafx;

import java.util.function.Function;
import java.util.regex.Pattern;

public class Validator {

	public static final boolean NO_CONVERSION = false; 
	public static final boolean CONVERT_UPPER = true;

	protected boolean convertUpperCase;
	protected Integer maxLength;
	protected String editMask;
	protected String validationMask;
	protected Function<String, Boolean> validationFunction;
	protected Pattern editMaskPattern;
	protected Pattern validationPattern;

	public Validator(boolean convertUpperCase, Integer maxLength, String editMask, String validationMask) {
		this(convertUpperCase, maxLength, editMask, validationMask, null);
	}

	public Validator(boolean convertUpperCase, Integer maxLength, String editMask, String validationMask,
			Function<String, Boolean> validationFunction) {
		super();
		this.convertUpperCase = convertUpperCase;
		this.maxLength = maxLength == null ? Integer.MAX_VALUE : maxLength;
		this.editMask = editMask;
		this.validationMask = validationMask;
		this.validationFunction = validationFunction;
		this.editMaskPattern = Pattern.compile(editMask);
		this.validationPattern = Pattern.compile(validationMask);
	}

	public boolean isConvertUpperCase() {
		return convertUpperCase;
	}

	public Integer getMaxLength() {
		return maxLength;
	}

	public String getEditMask() {
		return editMask;
	}

	public String getValidationMask() {
		return validationMask;
	}

	public Function<String, Boolean> getValidationFunction() {
		return validationFunction;
	}

	public boolean isValid(String text) {
		boolean patternMatches = validationPattern == null || validationPattern.matcher(text).matches();
		Boolean functionReturnsOK = getValidationFunction() == null || getValidationFunction().apply(text);
		return patternMatches && functionReturnsOK;
	}
}
